package com.muyu.system.service.impl;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.muyu.common.core.domain.Result;
import com.muyu.common.core.utils.DateUtils;
import com.muyu.common.core.utils.StringUtils;
import com.muyu.common.security.utils.SecurityUtils;
import com.muyu.common.system.domain.LoginUser;
import com.muyu.system.domain.*;
import com.muyu.system.dto.AddCartDTO;
import com.muyu.system.mapper.*;
import com.muyu.system.req.DanmoShoppingProductsPriceReq;
import com.muyu.system.service.IDanmoShoppingProductsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * 商品Service业务层处理
 *
 * @author yangle
 * @date 2024-09-29
 */
@Service
public class DanmoShoppingProductsServiceImpl implements IDanmoShoppingProductsService {
    @Autowired
    private DanmoShoppingProductsMapper danmoShoppingProductsMapper;

    @Autowired
    private DanmoShoppingFootprintMapper danmoShoppingFootprintMapper;
    @Autowired
    private DanmoShoppingSkuMapper danmoShoppingSkuMapper;

    @Autowired
    private DanmoShoppingReviewsMapper danmoShoppingReviewsMapper;

    @Autowired
    private DanmoShoppingProductsCollectionMapper danmoShoppingProductsCollectionMapper;

    @Autowired
   private DanmoProductFootprintMapper danmoProductFootprintMapper;

    @Autowired
    private DmShoppingGoodsMapper dmShoppingGoodsMapper;

    @Autowired
    private DanmoShoppingCartMapper danmoShoppingCartMapper;

    @Autowired
    private DmShoppingCartMapper dmShoppingCartMapper;

    @Autowired
    private DmShoppingSkuMapper dmShoppingSkuMapper;

    /**
     * 查询商品
     *
     * @param productId 商品主键
     * @return 商品
     */
    @Override
    public DanmoShoppingProducts selectDanmoShoppingProductsById(Long productId) {

        LoginUser loginUser = SecurityUtils.getLoginUser();
        // 查询商品足迹
        List<DanmoProductFootprint> danmoProductFootprintList = danmoProductFootprintMapper.selectProuct(loginUser.getUserid(), productId);
        // 1.先判断一下商品中是否有该商品的足迹
        if (danmoProductFootprintList != null && !danmoProductFootprintList.isEmpty()) {
            // 遍历列表更新每个足迹的时间
            for (DanmoProductFootprint danmoProductFootprint : danmoProductFootprintList) {
                // 将更新时间修改为当前时间
                danmoProductFootprint.setUpdateTime(DateUtils.getNowDate());
                danmoProductFootprintMapper.updateDanmoProductFootprint(danmoProductFootprint);
            }
        } else {
            DanmoProductFootprint build = DanmoProductFootprint.builder()
                    .userId(SecurityUtils.getLoginUser().getUserid())
                    .productId(productId)
                    .browseTime(DateUtils.getNowDate())
                    .types(1L)
                    .createTime(DateUtils.getNowDate())
                    .build();

            danmoProductFootprintMapper.insertDanmoProductFootprint(build);
        }

        DanmoShoppingProducts danmoShoppingProducts = danmoShoppingProductsMapper.selectDanmoShoppingProductsById(productId);
        List<DanmoShoppingReviews> danmoShoppingReviews = danmoShoppingReviewsMapper.selectDanmoShoppingReviewsByShoppingProductId(productId);
        danmoShoppingProducts.setDanmoShoppingProducts(danmoShoppingProductsMapper.selectDanmoShoppingProductsByCategoryTypeAndSubcategoryType(danmoShoppingProducts.getCategoryType(), danmoShoppingProducts.getSubcategoryType(), productId));
        danmoShoppingProducts.setDistribution(getNowDates());
        danmoShoppingProducts.setReviewCount((long) danmoShoppingReviews.size());

        // 计算评分
        if (!danmoShoppingReviews.isEmpty()) {
            long totalRating = 0;
            for (DanmoShoppingReviews danmoShoppingReview : danmoShoppingReviews) {
                totalRating += danmoShoppingReview.getRating();
            }
            double averageRating = (double) totalRating / danmoShoppingReviews.size();
            danmoShoppingProducts.setScore(averageRating);
        }

        DanmoShoppingProductsCollection danmoShoppingProductsCollection1 = danmoShoppingProductsCollectionMapper.selectDanmoShoppingProductsCollectionByProductsId(productId);
        if (danmoShoppingProductsCollection1 != null) {
            danmoShoppingProducts.setIsCollect("true");
        }
        return danmoShoppingProducts;
    }

    // 格式化配送时间
    public static String getNowDates() {
        LocalDateTime shippingDeadline = LocalDateTime.now().with(LocalTime.of(17, 0)); // 设置为当天17:00
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("M月d日");
        DateTimeFormatter formatterNow = DateTimeFormatter.ofPattern("M月d日 HH:mm");

        String formatNow = shippingDeadline.plusDays(1).format(formatterNow);
        String format = LocalDateTime.now().plusDays(getDeliveryDays()).format(formatter);
        String result = "承诺" + formatNow + "前发货，预计" + format + "前送达";
        return result;
    }

    // 判断当前时间是否超过中午12:00，并据此调整送达天数
    public static int getDeliveryDays() {
        LocalDateTime now = LocalDateTime.now();
        if (now.getHour() >= 12) {
            // 如果当前时间超过中午12:00，推后一天
            return 5; // 预计送达为外后天+1
        } else {
            return 4; // 预计送达为后天+1
        }
    }

    /**
     * 查询商品列表
     *
     * @param danmoShoppingProducts 商品
     * @return 商品
     */
    @Override
    public List<DanmoShoppingProducts> selectDanmoShoppingProductsList(DanmoShoppingProducts danmoShoppingProducts) {
        if (danmoShoppingProducts.getCategoryType() == null || danmoShoppingProducts.getCategoryType() == 1){
            danmoShoppingProducts.setCategoryType(null);
        }
        long[] keys = new long[]{1,2,3,4,5,6,7,8,9,10,11,12,13,14};
        if (danmoShoppingProducts.getSubcategoryType() != null){
            for (long key : keys) {
                if (danmoShoppingProducts.getSubcategoryType() == key){
                    danmoShoppingProducts.setSubcategoryType(null);
                    break;
                }
            }
        }
        return danmoShoppingProductsMapper.selectDanmoShoppingProductsList(danmoShoppingProducts);
    }

    /**
     * 新增商品
     *
     * @param danmoShoppingProducts 商品
     * @return 结果
     */
    @Transactional
    @Override
    public Result<String> insertDanmoShoppingProducts(DanmoShoppingProducts danmoShoppingProducts) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        danmoShoppingProducts.setCreateBy(loginUser.getUsername());
        danmoShoppingProducts.setCreateTime(DateUtils.getNowDate());
        danmoShoppingProducts.setUpdateBy(loginUser.getUsername());
        danmoShoppingProducts.setUpdateTime(DateUtils.getNowDate());
        danmoShoppingProducts.setId(generateOrderId());
        danmoShoppingProducts.setRating(0L);
        danmoShoppingProductsMapper.insertDanmoShoppingProducts(danmoShoppingProducts);
        Long id = danmoShoppingProducts.getId();
        danmoShoppingSkuListsetId(id, danmoShoppingProducts.getDanmoShoppingSkuList());
        danmoShoppingSkuMapper.insertDanmoShoppingSku(danmoShoppingProducts.getDanmoShoppingSkuList());
        for (DanmoShoppingSku danmoShoppingSku : danmoShoppingProducts.getDanmoShoppingSkuList()) {
            insertDanmoShoppingProductsAndSkuPicture(danmoShoppingSku);
        }
        insertDanmoShoppingProductsPicture(danmoShoppingProducts);
        return Result.success("添加成功");
    }

    /**
     * 新增商品类型图片信息
     *
     * @param danmoShoppingSku 商品类型对象
     */
    private void insertDanmoShoppingProductsAndSkuPicture(DanmoShoppingSku danmoShoppingSku) {
        List<DanmoShoppingProductsPicture> danmoShoppingProductsPictureList = danmoShoppingSku.getDanmoShoppingProductsPictureList();
        Long id = danmoShoppingSku.getId();
        if (StringUtils.isNotNull(danmoShoppingProductsPictureList)) {
            List<DanmoShoppingProductsPicture> list = new ArrayList<DanmoShoppingProductsPicture>();
            for (DanmoShoppingProductsPicture danmoShoppingProductsPicture : danmoShoppingProductsPictureList) {
                danmoShoppingProductsPicture.setProductId(id);
                list.add(danmoShoppingProductsPicture);
            }
            if (list.size() > 0) {
                danmoShoppingProductsMapper.batchDanmoShoppingProductsPicture(list);
            }
        }
    }

    private void danmoShoppingSkuListsetId(Long id, List<DanmoShoppingSku> danmoShoppingSkuList) {
        for (DanmoShoppingSku danmoShoppingSku : danmoShoppingSkuList) {
            danmoShoppingSku.setProductId(id);
        }
    }

    /**
     * 修改商品
     *
     * @param danmoShoppingProducts 商品
     * @return 结果
     */
    @Transactional
    @Override
    public Result<String> updateDanmoShoppingProducts(DanmoShoppingProducts danmoShoppingProducts) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        danmoShoppingProducts.setUpdateTime(DateUtils.getNowDate());
        danmoShoppingProducts.setUpdateBy(loginUser.getUsername());
        danmoShoppingProductsMapper.deleteDanmoShoppingProductsPictureByProductId(danmoShoppingProducts.getId());
//        根据商品id删除商品类型
        danmoShoppingSkuMapper.deleteDanmoShoppingSkuById(danmoShoppingProducts.getId());
//        新增商品类型
        Long id = danmoShoppingProducts.getId();
        danmoShoppingSkuListsetId(id, danmoShoppingProducts.getDanmoShoppingSkuList());
        danmoShoppingSkuMapper.insertDanmoShoppingSku(danmoShoppingProducts.getDanmoShoppingSkuList());

        insertDanmoShoppingProductsPicture(danmoShoppingProducts);
        danmoShoppingSkuMapper.updateDanmoShoppingSku(danmoShoppingProducts.getDanmoShoppingSkuList());
        danmoShoppingProductsMapper.updateDanmoShoppingProducts(danmoShoppingProducts);
        for (DanmoShoppingSku danmoShoppingSku : danmoShoppingProducts.getDanmoShoppingSkuList()) {
            insertDanmoShoppingProductsAndSkuPicture(danmoShoppingSku);
            danmoShoppingProductsMapper.deleteDanmoShoppingProductsPictureByProductId(danmoShoppingSku.getId());
        }
        return Result.success("修改成功");
    }

    /**
     * 批量删除商品
     *
     * @param ids 需要删除的商品主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteDanmoShoppingProductsByIds(Long[] ids) {
        danmoShoppingProductsMapper.deleteDanmoShoppingProductsPictureByProductIds(ids);
        for (Long productId : ids) {
            danmoShoppingSkuMapper.deleteDanmoShoppingSkuByIds(productId);
        }
        return danmoShoppingProductsMapper.deleteDanmoShoppingProductsByIds(ids);
    }

    /**
     * 删除商品信息
     *
     * @param id 商品主键
     * @return 结果
     */
/*    @Transactional
    @Override
    public int deleteDanmoShoppingProductsById(Long id) {
        danmoShoppingProductsMapper.deleteDanmoShoppingProductsPictureByProductId(id);
        DanmoShoppingProducts danmoShoppingProducts = danmoShoppingProductsMapper.selectDanmoShoppingProductsById(id);
        danmoShoppingSkuMapper.deleteDanmoShoppingSkuById(danmoShoppingProducts.getId());
        return danmoShoppingProductsMapper.deleteDanmoShoppingProductsById(id);
    }*/


    /**
     * 新增商品图片信息
     *
     * @param danmoShoppingProducts 商品对象
     */
    public void insertDanmoShoppingProductsPicture(DanmoShoppingProducts danmoShoppingProducts) {
        List<DanmoShoppingProductsPicture> danmoShoppingProductsPictureList = danmoShoppingProducts.getDanmoShoppingProductsPictureList();
        Long id = danmoShoppingProducts.getId();
        if (StringUtils.isNotNull(danmoShoppingProductsPictureList)) {
            List<DanmoShoppingProductsPicture> list = new ArrayList<DanmoShoppingProductsPicture>();
            for (DanmoShoppingProductsPicture danmoShoppingProductsPicture : danmoShoppingProductsPictureList) {
                danmoShoppingProductsPicture.setProductId(id);
                list.add(danmoShoppingProductsPicture);
            }
            if (list.size() > 0) {
                danmoShoppingProductsMapper.batchDanmoShoppingProductsPicture(list);
            }
        }
    }

    /**
     * 商品价格排序
     *
     * @param danmoShoppingProductsPriceReq
     * @return
     */
    @Override
    public List<DanmoShoppingProducts> selectPriceSort(DanmoShoppingProductsPriceReq danmoShoppingProductsPriceReq) {
        return danmoShoppingProductsMapper.selectPriceSort(danmoShoppingProductsPriceReq);
    }

    @Override
    public List<DanmoShoppingProducts> salesSortList(DanmoShoppingProductsPriceReq danmoShoppingProductsPriceReq) {
        return danmoShoppingProductsMapper.salesSortList(danmoShoppingProductsPriceReq);
    }

    @Override
    public List<DanmoShoppingProducts> commentsNumbersSort(DanmoShoppingProductsPriceReq danmoShoppingProductsCommentsNumbersReq) {
        return danmoShoppingProductsMapper.commentsNumbersSort(danmoShoppingProductsCommentsNumbersReq);

    }




    /*
     * AI优化前代码
     * 商品id 商品分类id 备注信息
     * */
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public Result addCart(AddCartDTO addCartDTO) {
        // 校验规格是否存在
        DmShoppingSku sku = new LambdaQueryChainWrapper<>(dmShoppingSkuMapper).eq(DmShoppingSku::getId, addCartDTO.getSkuId())
                .eq(DmShoppingSku::getGoodsId, addCartDTO.getGoodId()).one();
        if(null == sku){
            throw new RuntimeException("规格不存在");
        }
        // 查询是否有了购物车信息
        DmShoppingCart cart = new LambdaQueryChainWrapper<>(dmShoppingCartMapper).eq(DmShoppingCart::getUserId, addCartDTO.getUserId())
                .eq(DmShoppingCart::getGoodId, addCartDTO.getGoodId())
                .eq(DmShoppingCart::getSkuId, addCartDTO.getSkuId())
                .eq(DmShoppingCart::getStoreId, addCartDTO.getStoreId()).one();
        if(cart != null){
            cart.setQuantity(cart.getQuantity() + addCartDTO.getQuantity());
        }
        BeanUtil.copyProperties(addCartDTO, cart == null ? cart = new DmShoppingCart() : cart);
        if(cart.getId() == null){
            dmShoppingCartMapper.insert(cart);
        }else {
            dmShoppingCartMapper.updateById(cart);
        }
        return Result.success(1,"添加成功");
    }

    @Override
    public DanmoShoppingProducts selectDanmoShoppingProductsAndSkuById(Long productId, Long shoppingSkuId) {
        DanmoShoppingFootprint danmoShoppingFootprint;
        LoginUser loginUser = SecurityUtils.getLoginUser();
//        查询商品足迹
        danmoShoppingFootprint = danmoShoppingFootprintMapper.selectDanmoShoppingFootprintByUserIdAndProductId(loginUser.getUserid(),productId);
//        1.先判断一下商品中是否有该商品的足迹
        if (danmoShoppingFootprint != null) {
//            将更新时间修改为当前时间
            danmoShoppingFootprint.setUpdateTime(DateUtils.getNowDate());
            danmoShoppingFootprintMapper.updateDanmoShoppingFootprint(danmoShoppingFootprint);
        } else {
            danmoShoppingFootprint = new DanmoShoppingFootprint();
            danmoShoppingFootprint.setProductId(productId);
            danmoShoppingFootprint.setUserId(loginUser.getUserid());
            danmoShoppingFootprint.setCreateBy(loginUser.getUsername());
            danmoShoppingFootprint.setCreateTime(DateUtils.getNowDate());
            danmoShoppingFootprint.setUpdateBy(loginUser.getUsername());
            danmoShoppingFootprint.setUpdateTime(DateUtils.getNowDate());
            danmoShoppingFootprintMapper.insertDanmoShoppingFootprint(danmoShoppingFootprint);
        }
        DanmoShoppingProducts danmoShoppingProducts = danmoShoppingProductsMapper.selectDanmoShoppingProductsAndSkuById(productId, shoppingSkuId);
        danmoShoppingProducts.setDanmoShoppingSkuList(danmoShoppingSkuMapper.selectBydanmoShoppingSku(danmoShoppingProducts.getId()));
        return danmoShoppingProducts;
    }

    /**
     * 排行榜
     * @param danmoShoppingProductsPriceReq
     * @return
     */
    @Override
    public List<DanmoShoppingProductsPriceReq> commentsNumbersSortTop(DanmoShoppingProductsPriceReq danmoShoppingProductsPriceReq) {

        return List.of();
    }

/*    @Override
    public void addCart(DanmoShoppingProducts danmoShoppingProducts) {
        if (danmoShoppingProducts == null) {
            throw new IllegalArgumentException("查询商品失败");
        }

        DanmoShoppingCart danmoShoppingCart = createShoppingCart(danmoShoppingProducts);

        // 检查该用户是否已经购买过该商品
        DanmoShoppingCart existingCart = danmoShoppingCartMapper.selectByUserIDAndShoppingID(danmoShoppingCart);

        if (existingCart == null) {
            // 如果用户没有购买过该商品，添加新的购物车记录
            addNewCartItem(danmoShoppingCart);
        } else {
            // 如果用户已经购买过该商品，增加商品数量,但是下单商品数量不能大于商品库存量
            updateExistingCartItem(existingCart, danmoShoppingProducts);
        }
    }

    private DanmoShoppingCart createShoppingCart(DanmoShoppingProducts danmoShoppingProducts) {
        DanmoShoppingCart danmoShoppingCart = new DanmoShoppingCart();
        danmoShoppingCart.setProductId(danmoShoppingProducts.getId());
        danmoShoppingCart.setRemark(danmoShoppingProducts.getRemark());

        LoginUser loginUser = getCurrentLoginUser();
        danmoShoppingCart.setUserId(loginUser.getUserid());
        setCreationAndUpdateInfo(danmoShoppingCart, loginUser);

        return danmoShoppingCart;
    }

    private LoginUser getCurrentLoginUser() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (loginUser == null) {
            throw new RuntimeException("获取用户信息失败");
        }
        return loginUser;
    }

    private void setCreationAndUpdateInfo(DanmoShoppingCart danmoShoppingCart, LoginUser loginUser) {
        danmoShoppingCart.setCreateBy(loginUser.getUsername());
        danmoShoppingCart.setCreateTime(DateUtils.getNowDate());
        danmoShoppingCart.setUpdateBy(loginUser.getUsername());
        danmoShoppingCart.setUpdateTime(DateUtils.getNowDate());
    }

    private void addNewCartItem(DanmoShoppingCart danmoShoppingCart) {
        danmoShoppingCart.setQuantity(String.valueOf(1)); // 设置为整数类型
        danmoShoppingCartMapper.addCart(danmoShoppingCart);
    }

    private void updateExistingCartItem(DanmoShoppingCart existingCart, DanmoShoppingProducts danmoShoppingProducts) {
        int newQuantity = Integer.parseInt(existingCart.getQuantity() + 1);
        if (danmoShoppingProducts.getStock() < newQuantity) {
            throw new RuntimeException("添加失败");
        }
        existingCart.setQuantity(String.valueOf(newQuantity)); // 确保是整数类型
        danmoShoppingCartMapper.modifyTheQuantity(existingCart);
    }*/

    // 生成订单ID的方法
    private Long generateOrderId() {
        Random random = new Random();
        return Math.abs(random.nextLong()); // 确保生成的ID是正数
    }
}
